package com.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.model.GlobalResponse;
import com.mall.dao.ShippingMapper;
import com.mall.enums.GlobalResponseEnum;
import com.mall.form.ShippingForm;
import com.mall.pojo.Shipping;
import com.mall.service.IShippingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname ShippingServiceImpl
 * @Description
 * @Date 2022/7/31 14:23
 * @Created by TaoVh
 */
@Service
public class ShippingServiceImpl implements IShippingService {
    private ShippingMapper shippingMapper;

    @Autowired
    public void setShippingMapper(ShippingMapper shippingMapper) {
        this.shippingMapper = shippingMapper;
    }

    @Override
    public GlobalResponse<Map<String,Integer>> add(Integer uid, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form, shipping);
        shipping.setUserId(uid);
        int row = shippingMapper.insertSelective(shipping);
        if (row == 0) return GlobalResponse.error(GlobalResponseEnum.ERROR);


        HashMap<String , Integer> map = new HashMap<>();
        map.put("shippingId",shipping.getId());
        return GlobalResponse.successByData(map);
    }

    @Override
    public GlobalResponse delete(Integer uid, Integer shippingId) {
        int row = shippingMapper.deleteByIdAndUid(uid, shippingId);
        if (row==0) return GlobalResponse.error(GlobalResponseEnum.DELETE_SHIPPING_FAIL);
        return GlobalResponse.success();
    }

    @Override
    public GlobalResponse update(Integer uid, Integer shippingId, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(uid);
        shipping.setId(shippingId);
        int row = shippingMapper.updateByPrimaryKeySelective(shipping);
        if (row==0){
            return GlobalResponse.error(GlobalResponseEnum.ERROR);
        }
        return GlobalResponse.success();
    }

    @Override
    public GlobalResponse<PageInfo> list(Integer uid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippingList = shippingMapper.selectByUid(uid);
        PageInfo<List<Shipping>> pageInfo = new PageInfo(shippingList);
        return GlobalResponse.successByData(pageInfo);
    }
}
